package io.gatling.extensions.redis.action

import com.typesafe.scalalogging.StrictLogging
import io.gatling.commons.stats.OK
import io.gatling.commons.util.Clock
import io.gatling.core.CoreComponents
import io.gatling.core.action.{Action, ExitableAction}
import io.gatling.core.session.{Expression, Session}
import io.gatling.core.stats.StatsEngine
import io.gatling.core.util.NameGen
import redis.clients.jedis.{Jedis, JedisPool}


class RedisPoolGetAction(
                          val key: Expression[String],
                          val pool: JedisPool,
                          coreComponents: CoreComponents,
                          throttled: Boolean,
                          val next: Action
                        ) extends ExitableAction with NameGen with StrictLogging {

  import coreComponents._

  override def statsEngine: StatsEngine = coreComponents.statsEngine

  override def clock: Clock = coreComponents.clock

  override def name: String = genName("redis-pool-get-action")

  override def execute(session: Session): Unit = {

    key(session) map {
      value => {

        val requestStartDate = clock.nowMillis
        val jedis: Jedis = pool.getResource

        val resp: String = jedis.get(value)

        statsEngine.logResponse(
          session.scenario,
          session.groups,
          value,
          requestStartDate,
          clock.nowMillis,
          OK,
          Some(resp),
          Some(resp)
        )

        jedis.close()

        throttler match {
          case Some(th) if throttled => th.throttle(session.scenario, () => next ! session)
          case None => next ! session
        }
      }
    }
  }
}
